#!/usr/bin/env bash
. ./scripts/devcontainer/_assert-in-container "$0" "$@"

# Acquire the deploy lock. Required argument is the name for the lock, which should
# be a number (the build number) or "manual".

set -euo pipefail

LOCKFILE_NAME=$(./scripts/deployment/deploy-lock-one-get-name)

echo "Lock file: ${LOCKFILE_NAME}"

while true; do
  # Deploy locks start with a timestamp, so they can be sorted directly
  next=$( ./scripts/deployment/deploy-lock-all-list | sort -n | head -n 1)
  # smallest timestamp goes first
  if [[ "${next}" == "${LOCKFILE_NAME}"  ]]; then
    echo "We're up!"
    exit 0
  elif [[ "${next}" == "" ]]; then
    echo "No locks found, we're up!"
    exit 0
  else
    echo "Waiting for other deploy to finish (${next}), sleeping"
    sleep 5
  fi
done
